package com.mr3chi.horoscopes;

import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.todddavies.components.progressbar.ProgressWheel;

import android.app.DatePickerDialog.OnDateSetListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class FragmentNumberOfDay extends Fragment{
	
	private ProgressWheel 	mLoadBar;
	private LinearLayout 	mContent;
	
	private Button btTopDate;
	private Button btTopAct;
	
	private TextView 	tvCardTitle;
	private TextView 	tvCardContent;
	private Date 		currentDate = null;
	
	private NumberLoadingTask task = null;
	private OnDateSetListener ondate;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_number_of_day, container, false);
		
		ondate = new OnDateSetListener() {
			
			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear,
					int dayOfMonth) {
				Calendar cal = new GregorianCalendar(year, monthOfYear, dayOfMonth);
				currentDate = cal.getTime();
				
				SimpleDateFormat sdf = new SimpleDateFormat("MMM, dd yyyy",Locale.US);
				btTopDate.setText(sdf.format(currentDate));
			}
		};
		
		mLoadBar = (ProgressWheel) view.findViewById(R.id.fragment_number_loader);
		mLoadBar.spin();
		mContent = (LinearLayout) view.findViewById(R.id.fragment_number_info);
		
		btTopDate = (Button) view.findViewById(R.id.fragment_number_top_dateofbirth);
		btTopAct = (Button) view.findViewById(R.id.fragment_number_top_act);
		
		FacebookUser user = ((ActivityMain)getActivity()).getInfo();
		if(!user.getId().trim().equals("")){
			
		}
		
		btTopDate.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				FragmentTransaction ft = getChildFragmentManager().beginTransaction();
				DialogFragment newFragment = new DialogDatePicker(ondate);
				newFragment.show(ft, "date_dialog");
			}
		});
		
		btTopAct.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(checkDate()){
					if(((ActivityMain)getActivity()).hasConnection()){
						parseNumberOfDay();
					}else{
						Toast.makeText(getActivity(), R.string.error_no_intenet_connection, Toast.LENGTH_SHORT).show();
						setLoading(false);
						mContent.setVisibility(View.GONE);
					}
				}
				
			}
		});
		
		tvCardTitle = (TextView) view.findViewById(R.id.fragment_number_card_title);
		tvCardTitle.setText("Number of Day");
		tvCardContent = (TextView) view.findViewById(R.id.fragment_number_card_desc);
		
		AdView adView = (AdView)view.findViewById(R.id.adView);
		AdRequest adRequest = new AdRequest.Builder().build();
		adView.loadAd(adRequest);
		
		return view;
	}
	
	public boolean checkDate(){
		if(currentDate != null){
			Calendar today = Calendar.getInstance();
			Calendar bir = Calendar.getInstance();
			bir.setTime(currentDate);
			if(!bir.before(today)){
				Toast.makeText(getActivity(), R.string.fragment_number_error_birthday_after, Toast.LENGTH_SHORT).show();
				return false;
			}else{
				return true;
			}
		}else{
			Toast.makeText(getActivity(), R.string.fragment_number_error_birthday_none, Toast.LENGTH_SHORT).show();
			return false;
		}
		
	}
	
	public void parseNumberOfDay() {
		if(((ActivityMain)getActivity()).hasConnection()){
			setLoading(true);
			Calendar cal = Calendar.getInstance();
			cal.setTime(currentDate);
	        task = new NumberLoadingTask(cal.get(Calendar.DATE), cal.get(Calendar.MONTH), cal.get(Calendar.YEAR));
	        task.execute((Void) null);
        } else {
        	Toast.makeText(getActivity(), R.string.error_no_intenet_connection, Toast.LENGTH_SHORT).show();
        	setLoading(false);
        	mContent.setVisibility(View.GONE);
        }
	}
	
	public void setLoading(boolean load){
		if(load){
			if(mLoadBar.getVisibility()==View.VISIBLE) return;
			else{
				mLoadBar.setVisibility(View.VISIBLE);
				mContent.setVisibility(View.GONE);
				mLoadBar.spin();
			}
		}else{
			if(mLoadBar.getVisibility()==View.GONE) return;
			else{
				mLoadBar.setVisibility(View.GONE);
				mContent.setVisibility(View.VISIBLE);
				mLoadBar.stopSpinning();
			}
		}
	}
	
	public class NumberLoadingTask extends AsyncTask<Void, Void, List<String>>{
		
		private int day;
		private int month;
		private int year;
		
		public NumberLoadingTask(int dd, int mm, int yyyy) {
			day 	= dd;
			month 	= mm;
			year 	= yyyy;
		}
		
		@Override
		protected List<String> doInBackground(Void... params) {
			String ur 			= "http://m.dailyhoroscope.com/numerology/numerology-number-of-the-day/?member_birthdate_month=" + month + "&member_birthdate_day=" + day + "&member_birthdate_year=" + year;
			List<String> rs 	= new ArrayList<String>();
			String number 			= "";
			String numberMeaning 	= "";
			Document doc;
			
			try {
				URL url = new URL(ur);
				doc 	= Jsoup.parse(url.openStream(),"UTF-8",ur);
				
				Elements nodes = doc.select("h3.otd-heading");
				if(nodes != null && nodes.size() > 0){
					number = nodes.first().text();
				}
				
				nodes = doc.select("div.inner");
				if(nodes != null && nodes.size() > 0){
					numberMeaning = nodes.first().text();
				}
				
				rs.add(number);
				rs.add(numberMeaning);
	    		return rs;
	    		
			} catch (IOException e) {
			}
			return null;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			setLoading(true);
		}

		@Override
		protected void onPostExecute(List<String> result) {
			super.onPostExecute(result);
			if(result == null || result.size() != 2){
				Toast.makeText(getActivity(), R.string.error_notarot_here_yet, Toast.LENGTH_SHORT).show();
				setLoading(false);
				mContent.setVisibility(View.GONE);
			}else{
				tvCardTitle.setText(result.get(0));
				tvCardContent.setText(Html.fromHtml(result.get(1),null,null));
				if(mContent.getVisibility() != View.VISIBLE) mContent.setVisibility(View.VISIBLE);
				setLoading(false);
			}
			
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
			setLoading(false);
			task = null;
		}
	}
	
	
}
